package org.example.SolutionNew001;

import java.util.Arrays;

public class Array03 {
    public static void main(String[] args) {
        Array03 obj = new Array03();
        int[] nums=new int[]{1,2,3,4,5,6,7};
        obj.rotate(nums,3);
        System.out.println(Arrays.toString(nums));
    }

    public void rotate1(int[] nums, int k) {
        int n = nums.length;
        k=k%n;
        int[] tmp = new int[k];
        if(k==0) return;
        for(int i=n-k,j=0;i<n;i++,j++){
            tmp[j]=nums[i];
        }
        for(int i=n-k-1,j=n-1;i>=0;i--,j--){
            nums[j]=nums[i];
        }
        for(int i=0,j=0;i<k;i++,j++){
            nums[i]=tmp[j];
        }
//        System.out.println(Arrays.toString(nums));
    }

    public void rotate2(int[] nums, int k) {
        int n = nums.length;
        int[] nn=new int[n];
        for(int i=0;i<n;i++){
            nn[(i+k)%n]=nums[i];
        }
        System.arraycopy(nn,0,nums,0,n);
    }

    public void rotate3(int[] nums, int k) {
        int n = nums.length;
        int count=gcd(n,k);
        for(int start=0;start<count;start++){
            int current=start;
            int curValue=nums[start];
            do{
                int tmp=(current+k)%n;
                int tmpValue=nums[tmp];
                nums[tmp]=curValue;
                curValue=tmpValue;
                current=tmp;
            }while(current!=start);
        }
    }

    public int gcd(int a, int b) {
        return b==0? a:gcd(b,a%b);
    }

    public void rotate(int[] nums, int k) {
        int n = nums.length;
        k=k%n;
        reverse(nums,0,n-1);
        reverse(nums,0,k-1);
        reverse(nums,k,n-1);
    }

    public void reverse(int[] nums,int start,int end){
        while(start<end){
            int tmp=nums[start];
            nums[start]=nums[end];
            nums[end]=tmp;
            start++;
            end--;
        }
    }

}
